const fs = require('fs');
var path = require('path');
function createNewJson(src,dst,cb){
  console.log('---------- 合并package.json开始 ----------');
  let switcher = [false,false];
  let srcJson = {};
  let dstJson = {};
  fs.readFile(src, 'utf-8', function (err, data) {
    srcJson = JSON.parse(data);
    switcher[0] = true;
    if (switcher.indexOf(false) == -1) {
      makeNewJson();
    }
  });
  fs.readFile(dst, 'utf-8', function (err, data) {
    dstJson = JSON.parse(data);
    switcher[1] = true;
    if (switcher.indexOf(false) == -1) {
      makeNewJson();
    }
  });
  function makeNewJson(){/* 合并 创建新Json */
    //合并
    dstJson.dependencies = getMergedProps('dependencies');
    dstJson.devDependencies = getMergedProps('devDependencies');
    //创建新json
    fs.writeFile(dst, JSON.stringify(dstJson), function (err) {
      if (err) {
        console.log(err);
      }
      else {
        console.log('---------- 合并package.json结束 ----------');
        cb && cb();
      }
    });
    function getMergedProps(prop){
      let srcProp = srcJson[prop];
      let dstProp = dstJson[prop];
      for(let x in srcProp){
        for(let y in dstProp){
          if (x == y) {
            if (srcProp[x] != dstProp[y]) {
              dstProp[y] = getBiggerOne(srcProp[x],dstProp[y]);
            }
          }
          else{
            dstProp[x] = srcProp[x];
          }
        }
      }
      function getBiggerVersion(v1, v2) {
        function createArr(str) {
          let arr = str.split('.');
          return arr.map((value) => {
            return parseInt(value.replace(/[^0-9]/ig, ""));
          });
        }
        function getBig(index) {
          if (v1Arr[index] > v1Arr[index]) {
            return v1Arr;
          }
          else if (v1Arr[index] < v2Arr[index]) {
            return v2Arr;
          }
          else if (v1Arr[index] == v2Arr[index]) {
            return getBig(index + 1);
          }
        }
        v1Arr = createArr(v1);
        v2Arr = createArr(v2);
        return getBig(0);
      }
    }
  }
}

function copy(src, dst, cb) {
  var copyFile = function (srcPath, tarPath, cb) {
    var rs = fs.createReadStream(srcPath)
    rs.on('error', function (err) {
      if (err) {
        console.log('read error', srcPath)
      }
      cb && cb(err)
    })

    var ws = fs.createWriteStream(tarPath);
    ws.on('error', function (err) {
      if (err) {
        console.log('write error', tarPath)
      }
      cb && cb(err)
    })
    ws.on('close', function (ex) {
      cb && cb(ex)
    })

    rs.pipe(ws)
  }

  var copyFolder = function (srcDir, tarDir, cb) {
    fs.readdir(srcDir, function (err, files) {
      let len = files.length;
      var count = 0
      var checkEnd = function () {
        ++count == len && cb && cb()
      }

      if (err) {
        checkEnd()
        return
      }

      files.forEach(function (file) {
        if (file == 'package.json') {
          len = files.length -1;
          return;
        }
        var srcPath = path.join(srcDir, file)
        var tarPath = path.join(tarDir, file)

        fs.stat(srcPath, function (err, stats) {
          if (stats.isDirectory()) {
            fs.exists(tarPath, (exists) => {
              if (exists) {
                copyFolder(srcPath, tarPath, checkEnd)
              }
              else {
                fs.mkdir(tarPath, function (err) {
                  if (err) {
                    console.log(err)
                    return
                  }
                  copyFolder(srcPath, tarPath, checkEnd)
                })
              }
            })
          } else {
            copyFile(srcPath, tarPath, checkEnd)
          }
        })
      })

      //为空时直接回调
      len === 0 && cb && cb()
    })
  }
  fs.exists(dst, (exists) => {
    if (exists) {
      copyFolder(src, dst, () => {
        cb && cb();
      });
    }
    else {
      fs.mkdir(dst, () => {
        copyFolder(src, dst, () => {
          cb && cb();
        });
      });
    }
  });
}

module.exports = {
  copy: copy,
  createNewJson:createNewJson
}

